package com.rainng.coursesystem.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import com.rainng.coursesystem.service.FavouriteService;
import com.rainng.coursesystem.model.FavouriteItem;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

@RestController
@RequestMapping("/favourites")
public class FavouriteController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Autowired
    private FavouriteService favouriteService;

    @PostMapping("/uploadAndAdd")
    public ResponseEntity<String> uploadAndAddToFavourites(
            @RequestParam(required = false) String sNumber,
            @RequestParam(required = false) String tNumber, // 将 tNumber 参数标记为可选
            @RequestParam("file") MultipartFile file,
            @RequestParam(defaultValue = "false") boolean isPublic) {
        try {
            String message = favouriteService.uploadAndAddToFavourites(sNumber, tNumber, file, isPublic);
            return ResponseEntity.ok(message);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Failed to upload file and add to favourites: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    public ResponseEntity<List<FavouriteItem>> listFavourites(
            @RequestParam(required = false) String sNumber,
            @RequestParam(required = false) String tNumber) {
        List<FavouriteItem> items = favouriteService.listFavourites(sNumber,tNumber);
        return ResponseEntity.ok(items);
    }

    @GetMapping("/download/{fileId}")
    public ResponseEntity<Resource> downloadFile(@PathVariable UUID fileId) {
        try {
            Optional<FavouriteItem> optionalItem = Optional.ofNullable(favouriteService.getFavouriteById(fileId));
            if (optionalItem.isPresent()) {
                FavouriteItem item = optionalItem.get();

                Path filePath = Paths.get(item.getFileData());
                Resource resource = new UrlResource(filePath.toUri());

                if (!resource.exists() || !resource.isReadable()) {
                    return ResponseEntity.notFound().build();
                }

                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + item.getFileName() + "\"")
                        .contentType(MediaTypeFactory
                                .getMediaType(resource)
                                .orElse(MediaType.APPLICATION_OCTET_STREAM))
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (IOException e) {
            return ResponseEntity.status(500).body(null);
        }
    }

    @DeleteMapping("/remove")
    public ResponseEntity<String> removeFavourite(@RequestParam UUID fileId) {
        try {
            favouriteService.removeFavourite(fileId);
            return ResponseEntity.ok("File removed from favourites successfully.");
        } catch (Exception e) {
            return ResponseEntity.status(404).body("File not found in favourites: " + e.getMessage());
        }

    }

    @PutMapping("/visibility")
    public ResponseEntity<String> setFavouriteVisibility(
            @RequestParam(required = false) String sNumber,
            @RequestParam(required = false) String tNumber,
            @RequestParam boolean isPublic) {
        boolean updated = favouriteService.setFavouriteVisibility(sNumber, tNumber, isPublic);
        if (updated) {
            return ResponseEntity.ok("收藏夹可见性已更新.");
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping("/like")
    public ResponseEntity<String> likeFavourite(@RequestParam UUID fileId) {
        boolean liked = favouriteService.likeFavourite(fileId);
        if (liked) {
            return ResponseEntity.ok("收藏夹已点赞.");
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/public")
    public ResponseEntity<List<FavouriteItem>> browsePublicFavourites(
            @RequestParam(required = false) String sNumber,
            @RequestParam(required = false) String tNumber) {
        List<FavouriteItem> publicItems = favouriteService.listPublicFavourites(sNumber, tNumber);
        return ResponseEntity.ok(publicItems);
    }

}